#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    // 创建套接字
    int fd = socket(AF_INET, SOCK_DGRAM, 0);

    std::string serverip = "127.0.0.1";
    uint16_t serverport = 8888;

    struct sockaddr_in peer;
    memset(&peer, 0, sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(serverport);
    peer.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(peer);

    while (true)
    {
        std::string buf;
        printf("plese enter@ ");
        // gets(buf);
        std::getline(std::cin,buf);

        // 发送数据包
        int n = sendto(fd, buf.c_str(), sizeof(buf), 0, (struct sockaddr *)&peer, len);
        if(n < 0){
            std::cerr << "sendto error, err string:%s" << strerror(errno) <<std::endl;
        }

        // 接收数据包
        char tmp[1024] = {0};
        recvfrom(fd, tmp, 1023, 0, nullptr, nullptr);

        std::cout <<  tmp << std::endl;
    }
    return 0;
}
